// Copyright  2012 Petr TALLA. [petr.talla@gmail.com]
// This file is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This file is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY;  without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Lesser General Public License for more details.
// [http://www.gnu.org/copyleft/lesser.html]
//=============================================================================
package tc.common.utility;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.util.Vector;

import javax.swing.JPanel;

public class Dynbuff {
	public enum Buffer { SEL, CMD}; 
	
	static private Vector<DynbuffItem> itemsSel = new Vector<DynbuffItem>();
	static private Vector<DynbuffItem> itemsCmd = new Vector<DynbuffItem>();
	
	static Color colorOld;
	
	static public JPanel view = null;
	
	static void set(Graphics g) {
		colorOld = g.getColor();
		g.setColor(Color.BLACK);
		g.setXORMode(Color.WHITE);
	}
	
	static void reset(Graphics g) {
		g.setColor(colorOld);
		g.setPaintMode();
	}
	
	static public void dynamicBufferAdd(DynbuffItem item, Buffer buffer, JPanel viewArg ) {
		if (view != viewArg) {
			dynamicBufferClean();
			view = viewArg; 
		}
		
		Graphics g = view.getGraphics();
		
		switch (buffer) {
			case SEL: itemsSel.add(item); break;
			case CMD: itemsSel.add(item); break;
		}
		
		
		set(g);
		item.draw(g);
		reset(g);
	}
	
	static public void dynamicBufferPaint() {
		Graphics g = view.getGraphics();
		dynamicBufferPaint(g, itemsSel);
		dynamicBufferPaint(g, itemsCmd);
	}
	
	static private void dynamicBufferPaint(Graphics g, Vector<DynbuffItem> items ) {
		if (items.size() == 0) return;
		set(g);
		for (int i = 0; i < items.size(); i++) {
			items.get(i).draw(g);
		}
		reset(g);
	}
	
	static public void dynamicBufferClean() {
		if (view == null) return;
		Graphics g = view.getGraphics();
		dynamicBufferClean(g, itemsSel);
		dynamicBufferClean(g, itemsCmd);
		view = null;
	}
	
	static private void dynamicBufferClean(Graphics g, Vector<DynbuffItem> items ) {
		if (items.size() == 0) return;
		dynamicBufferPaint();
		items.clear();
	}
	
	static public void addCross(Point pt, JPanel viewArg) {
		DynbuffLine line;
		line = new DynbuffLine();
		line.points.add(new Point(pt.x-30, pt.y-10));
		line.points.add(new Point(pt.x+30, pt.y+10));
		Dynbuff.dynamicBufferAdd(line, Dynbuff.Buffer.CMD, viewArg);
		
		line = new DynbuffLine();
		line.points.add(new Point(pt.x+30, pt.y-10));
		line.points.add(new Point(pt.x-30, pt.y+10));
		Dynbuff.dynamicBufferAdd(line, Dynbuff.Buffer.CMD, viewArg);
	}
}


